package org.linlinjava.litemall.core.alibaba;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.logistics.param.AlibabaTradeGetLogisticsTraceInfoBuyerViewParam;
import com.alibaba.logistics.param.AlibabaTradeGetLogisticsTraceInfoBuyerViewResult;
import com.alibaba.ocean.rawsdk.ApiExecutor;
import com.alibaba.ocean.rawsdk.common.SDKResult;
import com.alibaba.trade.param.*;
import com.alibaba.tuna.fastjson.JSON;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.alibaba.po.OffersPo;
import org.linlinjava.litemall.core.alibaba.po.OrderGoodsOrmPo;
import org.linlinjava.litemall.core.config.GlobalConfig;
import org.linlinjava.litemall.db.domain.LitemallAddress;
import org.linlinjava.litemall.db.domain.LitemallOrder;
import org.linlinjava.litemall.db.domain.LitemallOrderGoods;
import org.linlinjava.litemall.db.service.LitemallAddressService;
import org.linlinjava.litemall.db.service.LitemallOrderGoodsService;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.db.util.PurchasingUntil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class AlibabaOrderService {
    private final Log logger = LogFactory.getLog(AlibabaOrderService.class);
    @Autowired
    private LitemallAddressService litemallAddressService;
    @Autowired
    private LitemallOrderService litemallOrderService;
    @Autowired
    private LitemallOrderGoodsService litemallOrderGoodsService;


    /**
     *
     * 查询物流详情
     * 根据阿里巴巴下单的orderId 查询 物流轨迹详情
     * */
    //alibaba.trade.getLogisticsTraceInfo.buyerView
    public SDKResult<AlibabaTradeGetLogisticsTraceInfoBuyerViewResult>  getLogisticsTraceInfo(Long orderId){
        AlibabaTradeGetLogisticsTraceInfoBuyerViewParam param = new AlibabaTradeGetLogisticsTraceInfoBuyerViewParam();
        param.setOrderId(orderId);
        param.setWebSite("1688");
        return  apiExecutor().execute(param);
    }

    /**
     * 1688取消订单
     * */
    public Boolean cancleOrder(Long tradeID,String cancelReason) {
        Boolean flag = false;
            AlibabaTradeCancelParam  param = new AlibabaTradeCancelParam();
            param.setWebSite("1688");
            param.setTradeID(tradeID);
            param.setCancelReason(cancelReason);
            SDKResult<AlibabaTradeCancelResult> result = apiExecutor().execute(param);
            if(result!=null&&result.getResult()!=null&&result.getResult().getSuccess()){
                flag = true;
            }else {
                if(result.getResult().getErrorCode()=="ORDER_NOT_EXIST"){
                    logger.info("1688errot订单不存在，设置为true");
                    flag=true;
                }else if(result.getResult().getErrorCode()=="400_3"){
                    logger.info("1688error 没有权限取消");
                }else if(result.getResult().getErrorCode()=="ORDER_STATUS_ERROR"){
                    logger.info("1688error 只能取消待支付的订单，已支付不可取消");
                }
            }
            return flag;
    }
    /***
     *
     * 溢价模式订单创建接口
     * com.alibaba.trade:alibaba.trade.createOrder4CybMedia-1
     * */
    public Object createOrder4CybMedia(Map<Long,List<OrderGoodsOrmPo>> map,LitemallOrder order) {
        logger.info("创建1688订单");

        /**
         * 订单预览
         * */

        AlibabaTradeFastAddress addressParam = new AlibabaTradeFastAddress();
        LitemallAddress address = litemallAddressService.findById(order.getAddressid());
        if (address != null) {
            addressParam.setFullName(address.getName());
            addressParam.setMobile(address.getTel());
            addressParam.setPhone(address.getTel());
            addressParam.setPostCode(getAddreddCode(address.getProvince() + address.getCity() + address.getCounty() + address.getAddressDetail()));
            addressParam.setCityText(address.getCity());
            addressParam.setProvinceText(address.getProvince());
            addressParam.setAreaText(address.getCounty());
            addressParam.setTownText(address.getAddressDetail());
            addressParam.setAddress(address.getProvince() + address.getCity() + address.getCounty() + address.getAddressDetail());
            addressParam.setDistrictCode(address.getAreaCode());
            ///接口中的地址id不知如何设置
            // addressParam.setAddressId(Long.valueOf(address.getId()));
        }
        Iterator<Map.Entry<Long, List<OrderGoodsOrmPo>>> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<Long, List<OrderGoodsOrmPo>> entry = entries.next();
            Long key = entry.getKey();
            List<OrderGoodsOrmPo> value = entry.getValue();
            logger.info("开始订单预览");
            AlibabaTradeFastCargo[] cargoParamList = new AlibabaTradeFastCargo[value.size()];
            for (int i = 0;i<value.size();i++){
                cargoParamList[i]=value.get(i).getTradeFastCargosPo();
            }
            SDKResult<AlibabaCreateOrderPreview4CybMediaResult> previewResult = this.orderPreview(addressParam, cargoParamList);




        /**
         * 订单预览结束
         * 开始创建订单
         * */
        if (previewResult.getResult().getSuccess()) {


            //order.setPurchasingPrice(previewResult.getResult().getOrderPreviewResuslt());
            //预览订单正常开始下单操作
            logger.info("订单预览Ok，开始下单接口调用");
            AlibabaTradeCreateOrder4CybMediaParam param = new AlibabaTradeCreateOrder4CybMediaParam();

            param.setAddressParam(addressParam);
            param.setCargoParamList(cargoParamList);
            if (order.getMessage() != null)
                param.setMessage(order.getMessage());
            Map<String, Object> po = new HashMap<>();

            // OuterOrderInfoPo po= new OuterOrderInfoPo();
            po.put("mediaOrderId", order.getId());
            po.put("phone", order.getMobile());
            List<OffersPo> listOffer = new ArrayList<>();
            // logger.info("开始循环插入offer数据");
            for (AlibabaTradeFastCargo cargo : cargoParamList) {
                OffersPo offer = new OffersPo();
                offer.setId(cargo.getOfferId());
                offer.setNum(cargo.getQuantity().intValue());
                offer.setSpecId(cargo.getSpecId());
                offer.setPrice(order.getActualPrice().multiply(new BigDecimal(100)).longValue());  //媒体溢价是个什么鬼 得咨询对接人员
                // logger.info("offerd打印:::"+JSON.toJSON(offer));
                listOffer.add(offer);
            }
            // logger.info("数据插入结束::::"+JSON.toJSON(listOffer));

            po.put("offers", listOffer);
            //logger.info("媒体溢价创建订单入参打印:::"+JSON.toJSON(po));
            param.setOuterOrderInfo(new JSONObject(po).toJSONString());

            SDKResult<AlibabaTradeCreateOrder4CybMediaResult> createResult = apiExecutor().execute(param);
            if ((createResult.getErrorCode() == null || createResult.getErrorCode() == "") && createResult.getResult() != null) {
                if (createResult.getResult().getSuccess()) {
                    //下单成功
                    /**
                     * 判断是否自动支付订单,
                     * 设置一个风险校验值，若订单金额+运费+风险校验值 > 订单实际支付金额，则不自动支付，
                     * 通知管理员进行后台校验
                     * 若 下单成功金额+运费+风险校验值<= 订单实际支付金额，则系统自动代扣支付，等待发货
                     * */
                    logger.info("1688下单成功，等待支付");
                    //跟新子订单表
                   LitemallOrderGoods orderGoods = new LitemallOrderGoods();
                   orderGoods.setAlibabaOrderid(createResult.getResult().getResult().getOrderId());
                   orderGoods.setPurchasingStatus(PurchasingUntil.STATUS_PURCHASING_WAIT2PAY);
                   orderGoods.setOrderId(value.get(value.size()-1).getLitemallOrderGoodsPo().getOrderId());
                   orderGoods.setGoodsId(value.get(value.size()-1).getLitemallOrderGoodsPo().getGoodsId());

                    litemallOrderGoodsService.updateByOrderIdGoodsId(orderGoods);

                  //跟新主订单表
                    order.setAlibabaOrderid(createResult.getResult().getResult().getOrderId());
                    order.setPurchasingStatus(PurchasingUntil.STATUS_PURCHASING_WAIT2PAY);
                    litemallOrderService.updateLitemallOrder(order);

                    //调用支付接口进行支付
                    //此处自动支付暂时关闭，先通过人工支付的渠道进行数据收集
//                    Boolean payrest = this.payTo1688(createResult.getResult().getResult());
//                    if (payrest) {
//                        //订单支付成功,此处开始更新订单状态，等待物流信息
//                        logger.info("订单支付成功，等待厂家发货");
//                        order.setPurchasingStatus(PurchasingUntil.STATUS_PURCHASING_PAYD);
//
//                        litemallOrderService.updateWithOptimisticLocker(order);
//
//
//                    }
                } else {
                    order.setPurchasingStatus(PurchasingUntil.STATUS_PURCHASING_FAIL);
                    order.setPurchasingFailReason(createResult.getResult().getErrorMsg());
                    litemallOrderService.updateWithOptimisticLocker(order);

                    //获取下单失败商品信息,进行后续业务处理
                }
            } else {
                logger.info("创建订单失败，速速查看原因:" + JSON.toJSON(createResult));
                //后续要发管理员通知
            }


        } else {
            //预览订单报错,根据错误提示机型修改
            logger.info("订单预览失败，请根据错误信息修改:" + previewResult.getResult().getErrorMsg());
            return previewResult.getResult();
        }
    }

            return "订单创建成功";


        //执行下单操作



    }
    /**
     * 溢价模式创建订单前预览数据接口
     * com.alibaba.trade:alibaba.createOrder.preview4CybMedia-1
     * */
    public SDKResult<AlibabaCreateOrderPreview4CybMediaResult> orderPreview( AlibabaTradeFastAddress addressParam,AlibabaTradeFastCargo[] cargoParamList){
        AlibabaCreateOrderPreview4CybMediaParam param = new AlibabaCreateOrderPreview4CybMediaParam();
       param.setCargoParamList(cargoParamList);
       param.setAddressParam(addressParam);
       return apiExecutor().execute(param);


    }


    ///此方法已经废弃，当前应用无权限调用 快速创建订单接口,必须先预览订单
    /**
     *      private String flow; //流程(general 大市场订单,saleproxy 代销市场订单 fenxiao 淘货源下单)
     *     private Long subUserId;  //子账号（非必须）
     *     private String message; // 买家留言(非必须)
     *     private AlibabaTradeFastAddress addressParam; //收货地址
     *     private AlibabaTradeFastCargo[] cargoParamList; //商品信息
     *     private AlibabaTradeFastInvoice invoiceParam;  // 发票信息(非必须)
     *     private String shopPromotionId;  //店铺优惠id( 非必须)
     * */
//    public void  create1688OrderAuto(AlibabaTradeFastCargo[]  cargoParamList, LitemallOrder order){
//
//        logger.info("创建1688订单");
//
//        AlibabaTradeFastAddress addressParam = new AlibabaTradeFastAddress();
//        //List<AlibabaTradeFastCargo>  cargoParamList = new ArrayList<AlibabaTradeFastCargo>();
//        AlibabaTradeFastCreateOrderParam param = new AlibabaTradeFastCreateOrderParam();
//        param.setFlow("saleproxy");
//        param.setMessage(order.getMessage()!=null?order.getMessage():null);
//        LitemallAddress address =  litemallAddressService.findById(order.getAddressid());
//        if(address!=null){
//
//            addressParam.setFullName(order.getConsignee());
//            addressParam.setMobile(address.getTel());
//            addressParam.setPhone(order.getMobile());
//            addressParam.setPostCode(getAddreddCode(order.getAddress()));
//            addressParam.setCityText(address.getCity());
//            addressParam.setProvinceText(address.getProvince());
//            addressParam.setAreaText(address.getCounty());
//            addressParam.setTownText(address.getAddressDetail());
//            addressParam.setAddress(address.getAddressDetail());
//            addressParam.setDistrictCode(address.getAreaCode());
//            ///接口中的地址id不知如何设置
//            addressParam.setAddressId(Long.valueOf(address.getId()));
//        }
//        param.setAddressParam(addressParam);
//        param.setCargoParamList(cargoParamList);
//        logger.info(param);
//        //执行下单操作
//       SDKResult<AlibabaTradeFastCreateOrderResult> createResult = apiExecutor().execute(param);
//       if((createResult.getErrorCode()==null||createResult.getErrorCode()=="")&&createResult.getResult()!=null){
//                if(createResult.getResult().getSuccess()){
//                    //下单成功
//                    /**
//                     * 判断是否自动支付订单,
//                     * 设置一个风险校验值，若订单金额+运费+风险校验值 > 订单实际支付金额，则不自动支付，
//                     * 通知管理员进行后台校验
//                     * 若 下单成功金额+运费+风险校验值<= 订单实际支付金额，则系统自动代扣支付，等待发货
//                     * */
//
//                    //将1688orderId 维护到系统数据库中
//                    order.setAlibabaOrderid(createResult.getResult().getResult().getOrderId());
//                    litemallOrderService.updateWithOptimisticLocker(order);
//                    if(createResult.getResult().getResult().getPostFee()>2000){
//                        //邮费高于20 是否是特殊地区
//                        logger.info("邮费高于20");
//                        return;
//                    }
//                    if((createResult.getResult().getResult().getTotalSuccessAmount()+createResult.getResult().getResult().getPostFee()) > (order.getActualPrice().multiply(new BigDecimal(100)).longValue())){
//                        //进货价大于实际订单支付价格
//                        logger.info("下单价格大于销售价格");
//                        return;
//                    }
//                    //调用支付接口进行支付
//                   Boolean payrest= this.payTo1688(createResult.getResult().getResult()d);
//                    if(payrest){
//                        //订单支付成功,此处开始更新订单状态，等待物流信息
//
//                       // order.setOrderStatus(OrderUtil.STATUS_SHIP);
//
//                       // litemallOrderService.updateWithOptimisticLocker(order);
//
//
//                    }
//                }else {
//                    //获取下单失败商品信息,进行后续业务处理
//                }
//       }else {
//           logger.info("创建订单失败，速速查看原因:"+JSON.toJSON(createResult));
//           //后续要发管理员通知
//       }
//    }
    /***
     * 支付宝协议代扣支付
     * 传入参数,1688orderId
     * */
    public Boolean payTo1688(AlibabaTradeFastResult fastResult){
        Boolean flag = false;
//        if (result.getPostFee() > 2000) {
//            //邮费高于20 是否是特殊地区
//            logger.info("邮费高于20");
//            return flag;
//        }
//        if ((result.getTotalSuccessAmount() + result.getPostFee()) > (order.getActualPrice().multiply(new BigDecimal(100)).longValue())) {
//            //进货价大于实际订单支付价格
//            logger.info("下单价格大于销售价格");
//            return createResult.getResult().getResult();
//        }
        AlibabaTradePayProtocolPayParam param = new AlibabaTradePayProtocolPayParam();
        param.setOrderId(Long.valueOf(fastResult.getOrderId().toString()));
        SDKResult<AlibabaTradePayProtocolPayResult> result = apiExecutor().execute(param);
        if(result.getErrorCode()!=null&&Integer.valueOf(result.getErrorCode())>0){
            logger.info("1688支付失败,失败原因:"+result.getResult().getMessage());

        }else if(result.getResult().getSuccess()) {
            logger.info("1688支付成功");
            flag = true;
        }else {
            logger.info("1688代扣异常 :"+ JSON.toJSON(result));
        }
        return flag;

    }
    /**
     * 根据地址信息获取邮编
     * */
    public String getAddreddCode(String addressDetail){
        AlibabaTradeAddresscodeParseParam param = new AlibabaTradeAddresscodeParseParam();
        String result = "000000";
        param.setAddressInfo(addressDetail);
         SDKResult<AlibabaTradeAddresscodeParseResult> codeparseResult = apiExecutor().execute(param);
         if(codeparseResult.getResult()!=null)
             result=codeparseResult.getResult().getResult().getPostCode();
        return  result;

    }
    private ApiExecutor apiExecutor(){
        //获取配置信息appid和appsecret
        ApiExecutor apiExecutor = new ApiExecutor(GlobalConfig.AlibabaAppId,GlobalConfig.AlibabaAppSecret);
        return apiExecutor;
    }

}
